<template>
  <AdminLayout>
    <el-card class="add-question-card">
      <template #header>
        <div class="card-header">
          <span>编辑题目</span>
        </div>
      </template>
        
        <el-form
          ref="questionFormRef"
          :model="questionForm"
          :rules="rules"
          label-width="100px"
          class="question-form"
        >
          <!-- 所属课程 -->
          <el-form-item label="所属课程" prop="courseId">
            <el-select v-model="questionForm.courseId" placeholder="请选择课程" style="width: 240px;">
              <el-option
                v-for="course in courseList"
                :key="course.courseId"
                :label="course.courseName"
                :value="course.courseId"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 题型 -->
          <el-form-item label="题型" prop="typeId">
            <el-select
              v-model="questionForm.typeId"
              placeholder="请选择题型"
              style="width: 240px;"
              @change="handleTypeChange"
            >
              <el-option
                v-for="type in questionTypeList"
                :key="type.typeId"
                :label="type.typeName"
                :value="type.typeId"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 题目内容 -->
          <el-form-item label="题目内容" prop="questionContent">
            <el-input
              v-model="questionForm.questionContent"
              type="textarea"
              :rows="4"
              placeholder="请输入题目内容"
            ></el-input>
          </el-form-item>

          <!-- 选项输入区域（仅单选题和多选题显示） -->
          <template v-if="showOptions">
            <el-form-item label="选项A" prop="optionA" v-if="questionForm.typeId !== 3">
              <el-input
                v-model="questionForm.optionA"
                placeholder="请输入选项A"
                style="width: 400px;"
              ></el-input>
            </el-form-item>

            <el-form-item label="选项B" prop="optionB" v-if="questionForm.typeId !== 3">
              <el-input
                v-model="questionForm.optionB"
                placeholder="请输入选项B"
                style="width: 400px;"
              ></el-input>
            </el-form-item>

            <el-form-item label="选项C" prop="optionC" v-if="questionForm.typeId !== 3">
              <el-input
                v-model="questionForm.optionC"
                placeholder="请输入选项C"
                style="width: 400px;"
              ></el-input>
            </el-form-item>

            <el-form-item label="选项D" prop="optionD" v-if="questionForm.typeId !== 3">
              <el-input
                v-model="questionForm.optionD"
                placeholder="请输入选项D"
                style="width: 400px;"
              ></el-input>
            </el-form-item>
          </template>

          <!-- 判断题特殊处理 -->
          <template v-if="questionForm.typeId === 3">
            <el-form-item label="正确答案" prop="correctAnswer">
              <el-radio-group v-model="questionForm.correctAnswer">
                <el-radio label="A">对</el-radio>
                <el-radio label="B">错</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>

          <!-- 非判断题的正确答案 -->
          <el-form-item label="正确答案" prop="correctAnswer" v-if="questionForm.typeId !== 3">
            <el-input
              v-model="questionForm.correctAnswer"
              placeholder="请输入正确答案（如：A、B、AB等）"
              style="width: 240px;"
            ></el-input>
            <div class="answer-hint">
              <el-tag size="small" type="info">提示：单选题请输入单个字母，多选题请输入多个字母（如AB）</el-tag>
            </div>
          </el-form-item>

          <!-- 题目分值 -->
          <el-form-item label="题目分值" prop="score">
            <el-input-number
              v-model.number="questionForm.score"
              :min="0.5"
              :max="100"
              :step="0.5"
              style="width: 240px;"
              placeholder="请输入分值"
            ></el-input-number>
          </el-form-item>

          <!-- 难度等级 -->
          <el-form-item label="难度等级" prop="difficulty">
            <el-select v-model="questionForm.difficulty" placeholder="请选择难度等级" style="width: 240px;">
              <el-option label="简单" value="简单"></el-option>
              <el-option label="中等" value="中等"></el-option>
              <el-option label="困难" value="困难"></el-option>
            </el-select>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <div class="form-actions">
              <el-button type="primary" @click="handleSubmit">保存修改</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button @click="handleCancel">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </AdminLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { get, postJson } from '@/utils/api'
import { useRouter, useRoute } from 'vue-router'
import TeacherLayout from '../../components/teacher/TeacherLayout.vue'
import AdminLayout from '../../components/admin/AdminLayout.vue'

const router = useRouter()
const route = useRoute()

// 表单引用
const questionFormRef = ref<FormInstance>()

// 课程列表
const courseList = ref<any[]>([])

// 题型列表
const questionTypeList = ref<any[]>([])

// 题目表单数据
const questionForm = reactive({
  questionId: null as number | null,
  teacherId: null as number | null,
  courseId: null as number | null,
  typeId: null as number | null,
  questionContent: '',
  optionA: '',
  optionB: '',
  optionC: '',
  optionD: '',
  correctAnswer: '',
  score: 0,
  difficulty: ''
})

// 是否显示选项（根据题型判断）
const showOptions = computed(() => {
  return questionForm.typeId !== null && questionForm.typeId !== undefined
})

// 表单验证规则
const rules = reactive<FormRules>({
  courseId: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  typeId: [
    { required: true, message: '请选择题型', trigger: 'change' }
  ],
  questionContent: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 5, max: 500, message: '题目内容长度在 5 到 500 个字符', trigger: 'blur' }
  ],
  optionA: [
    { 
      validator: (rule, value, callback) => {
        if ((questionForm.typeId === 1 || questionForm.typeId === 2) && !value) {
          callback(new Error('请输入选项A'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    },
    { min: 1, max: 200, message: '选项A长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  optionB: [
    { 
      validator: (rule, value, callback) => {
        if ((questionForm.typeId === 1 || questionForm.typeId === 2) && !value) {
          callback(new Error('请输入选项B'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    },
    { min: 1, max: 200, message: '选项B长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  optionC: [
    { required: false },
    { min: 1, max: 200, message: '选项C长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  optionD: [
    { required: false },
    { min: 1, max: 200, message: '选项D长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  correctAnswer: [
    { required: true, message: '请输入正确答案', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入正确答案'))
        } else if (questionForm.typeId === 1) {
          // 单选题验证：只能是A/B/C/D中的一个
          if (!/^[ABCD]$/.test(value)) {
            callback(new Error('单选题答案只能是A、B、C、D中的一个'))
          } else {
            callback()
          }
        } else if (questionForm.typeId === 2) {
          // 多选题验证：只能包含A/B/C/D，并且不重复
          if (!/^[ABCD]+$/.test(value)) {
            callback(new Error('多选题答案只能包含A、B、C、D'))
          } else {
            // 检查是否有重复字符
            const uniqueChars = [...new Set(value.split(''))]
            if (uniqueChars.length !== value.length) {
              callback(new Error('多选题答案不能有重复字符'))
            } else {
              callback()
            }
          }
        } else if (questionForm.typeId === 3) {
          // 判断题验证：只能是A或B
          if (!/^[AB]$/.test(value)) {
            callback(new Error('判断题答案只能是A(对)或B(错)'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  score: [
    { required: true, message: '请输入题目分值', trigger: 'blur' },
    { type: 'number', min: 0.5, max: 100, message: '分值在 0.5 到 100 之间', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ]
})

// 获取题型列表
const fetchQuestionTypes = async () => {
  try {
    const response = await get('/question-type/query')
    if (response.code === 200) {
      questionTypeList.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取题型列表失败')
    }
  } catch (error) {
    console.error('获取题型列表异常:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 获取课程列表
const fetchCourses = async () => {
  try {
    const response = await get('/course/query/all')
    if (response.code === 200) {
      courseList.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取课程列表失败')
    }
  } catch (error) {
    console.error('获取课程列表异常:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 获取题目详情
const fetchQuestionDetail = async (questionId: number) => {
  try {
    // 这里应该调用获取单个题目详情的接口
    // 假设后端提供了这个接口，或者我们可以从列表数据中筛选
    // 为了演示，我们使用查询列表接口，然后筛选出指定ID的题目
    const response = await get('/question-bank/query', { questionId })
    
    if (response.code === 200 && response.data && response.data.length > 0) {
      const question = response.data[0]
      // 填充表单数据
      questionForm.questionId = question.questionId
      questionForm.teacherId = question.teacherId || null
      questionForm.courseId = question.courseId
      questionForm.typeId = question.typeId
      questionForm.questionContent = question.questionContent
      questionForm.optionA = question.optionA || ''
      questionForm.optionB = question.optionB || ''
      questionForm.optionC = question.optionC || ''
      questionForm.optionD = question.optionD || ''
      questionForm.correctAnswer = question.correctAnswer
      questionForm.score = question.score || 0
      questionForm.difficulty = question.difficulty
    } else {
      ElMessage.error('题目不存在或已被删除')
      router.push('/teacher/question/list')
    }
  } catch (error) {
    console.error('获取题目详情异常:', error)
    ElMessage.error('网络错误，请稍后重试')
    router.push('/teacher/question/list')
  }
}

// 题型变化时重置相关字段
const handleTypeChange = () => {
  // 重置选项和答案
  questionForm.optionA = ''
  questionForm.optionB = ''
  questionForm.optionC = ''
  questionForm.optionD = ''
  questionForm.correctAnswer = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!questionFormRef.value) return
  
  try {
    await questionFormRef.value.validate()
    
    // 准备提交数据
    const submitData = {
      questionId: questionForm.questionId,
      teacherId: questionForm.teacherId, // 保留原有教师ID
      courseId: questionForm.courseId,
      typeId: questionForm.typeId,
      questionContent: questionForm.questionContent,
      optionA: questionForm.optionA,
      optionB: questionForm.optionB,
      optionC: questionForm.optionC,
      optionD: questionForm.optionD,
      correctAnswer: questionForm.correctAnswer,
      score: questionForm.score,
      difficulty: questionForm.difficulty
    }
    
    // 发送请求（使用JSON格式）
    const response = await postJson('/question-bank/update', submitData)
    
    if (response.code === 200) {
      ElMessage.success(response.msg || '题目修改成功')
      // 返回列表页
      router.push('/teacher/question/list')
    } else {
      ElMessage.error(response.msg || '题目修改失败')
    }
  } catch (error) {
    console.error('提交表单异常:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 重置表单
const handleReset = () => {
  if (questionFormRef.value) {
    questionFormRef.value.resetFields()
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/teacher/question/list')
}

// 页面挂载时获取数据
onMounted(async () => {
  // 获取题目ID
  const questionId = Number(route.query.id)
  if (!questionId || isNaN(questionId)) {
    ElMessage.error('无效的题目ID')
    router.push('/teacher/question/list')
    return
  }
  
  // 并行获取基础数据和题目详情
  await Promise.all([
    fetchQuestionTypes(),
    fetchCourses(),
    fetchQuestionDetail(questionId)
  ])
})
</script>

<style scoped>
.add-question-card {
  width: 100%;
  max-width: 800px;
  margin: 20px auto;
  flex: 1;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  text-align: center;
}

.question-form {
  margin-top: 20px;
}

.answer-hint {
  margin-top: 8px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 30px;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-question-card {
    margin: 10px;
    max-width: 100%;
  }
  
  .el-input,
  .el-select,
  .el-input-number {
    width: 100% !important;
  }
}
</style>